package viewcomponents;

import java.awt.Dimension;
import java.awt.Graphics;
import java.util.List;

import javax.swing.JPanel;

import view.Observer;

import model.turtle.Position;
import model.turtle.Turtle;

/**
 * Class for showing turtle and its trail
 *
 */
public class TurtleCanvas extends JPanel implements Observer
{
	private int DEFAULT_SIZE = 600;
	
	private List<Turtle> myTurtles;
	private static final double dimension = 20;
	private int[] x;
	private int[] y;
	
	public TurtleCanvas()
	{
		setPreferredSize(new Dimension(DEFAULT_SIZE,DEFAULT_SIZE));
		//setBackground(Color.WHITE);
		setVisible(true);
		
		x = new int[3];
		y = new int[3];
	}
	
	/**
	 * Update turtle information and paint turtle's new trail
	 */
	public void update(List<Turtle> turtles)
	{
		this.myTurtles = turtles;
		repaint();
	}
	
	@Override
	public void paint(Graphics g)
	{
		if(myTurtles == null)
			return;
		
		for (Turtle turtle: myTurtles){
			List<Position> trail = turtle.getTrail();
			if(trail.size()==0)
				return;
			Position swap = trail.remove(0);
			while(trail.size()!=0){
				g.drawLine(DEFAULT_SIZE/2+(int)swap.x, 
						   DEFAULT_SIZE/2-(int)swap.y, 
						   DEFAULT_SIZE/2+(int)trail.get(0).x, 
						   DEFAULT_SIZE/2-(int)trail.get(0).y);
				swap = trail.remove(0);
			}
			trail.add(swap);
			
			Position p = turtle.getPosition();
			x[0] = (int) (p.x + Math.cos(p.getDirection()) * dimension);
			y[0] = (int) (p.y + Math.sin(p.getDirection()) * dimension);
			x[1] = (int) (p.x + Math.cos(p.getDirection() + 2.35619) * dimension
					/ 2);
			y[1] = (int) (p.y + Math.sin(p.getDirection() + 2.35619) * dimension
					/ 2);
			x[2] = (int) (p.x + Math.cos(p.getDirection() - 2.35619) * dimension
					/ 2);
			y[2] = (int) (p.y + Math.sin(p.getDirection() - 2.35619) * dimension
					/ 2);
			g.drawPolygon(x, y, 3);
		}
	}
}
